import React, { Component } from 'react';
import {
  Card,
  Button,
  Table,
  Menu,
  Input,
  Divider,
  Popconfirm,
  Modal,
  message,
  Radio
} from 'antd';
import { connect } from 'dva';
import PartsCategoryItem from './components/PartsCategory';
import config from '../../../config/web.config'
import styles from './index.less';
import { getValueWithLocalStorage, getOwner } from '@/utils/authority';


const namespace = 'Inventory';
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const { Search, TextArea } = Input;

const mapStateToProps = state => {
  const category = state[namespace].category;
  const custom = category.custom;
  const system = category.system;
  const isLoading = state[namespace].categoryLoading;

  return {
    system,
    custom,
    isLoading,
  };
};

const mapDispatchToProps = dispatch => {
  return {
    getList: (params) => {
      const action = {
        type: `${namespace}/queryCategory`,
        payload: {
          ...params,
          owner: getOwner(),
        },
      };
      dispatch(action);
    },
    saveItem: (values) => {
      const action = {
        type: `${namespace}/saveCategory`,
        payload: {
          ...values,
          owner: getOwner(),
        },
      };
      return dispatch(action);
    },
    editItem: (values) => {
      const action = {
        type: `${namespace}/editCategory`,
        payload: {
          ...values,
        },
      };
      return dispatch(action);
    },
    delItem: (_id) => {
      const action = {
        type: `${namespace}/delCategory`,
        payload: {
          id: _id,
        },
      };
      return dispatch(action);
    },
  };
};

@connect(
  mapStateToProps,
  mapDispatchToProps
)
export default class ContactList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      type: '0',
      key: '',
      toptypeid: null,
      modalVisible: false,
      itemData: {},
      modalLoading: false,
    };
    // this.formRef = React.createRef();
  }

  componentDidMount() {
    config.loadlCNZZ()
    this.reloadData();
  }

  reloadData = (params) => {
    const { type, key } = this.state;
    this.props.getList({ type: type, key: key, ...params });
  };

  // 新建
  handleCreateItem = (record, event) => {
    event.preventDefault();
    this.setState({
      modalVisible: true,
      itemData: {},
      toptypeid: record ? record._id : null
    });
  }

  // 编辑
  handleEditItem = (record, event) => {
    event.preventDefault();
    this.setState({
      modalVisible: true,
      itemData: record,
      toptypeid: record.toptypeid
    });
  }

  handleDelItem = (id) => {
    const { delItem } = this.props;
    delItem(id).then(res => {
      if (res.code === 1) {
        message.success("删除配件分类成功");
        this.reloadData()
      } else {
        message.error(res.msg || "删除配件分类失败");
      }
    });
  }

  handleModalOk = () => {
    this.formInstance.handleSubmit();
  }

  handleModalCancel = () => {
    this.setState({
      modalVisible: false,
    });
  }

  handleSaveForm = (values) => {
    const { editItem, saveItem } = this.props;
    this.setState({
      modalLoading: true
    });
    // 添加大类id
    values.toptypeid = this.state.toptypeid;
    if (values.id) {
      editItem(values).then(res => {
        if (res.code === 1) {
          message.success("编辑配件分类成功");
          this.setState({
            modalVisible: false,
            modalLoading: false,
            itemData: {}
          }, this.reloadData);
        } else {
          message.error(res.msg || "编辑配件分类失败");
          this.setState({
            modalLoading: false,
          });
        }
      })
    } else {
      saveItem(values).then(res => {
        if (res.code === 1) {
          message.success("新增配件分类成功");
          this.setState({
            modalVisible: false,
            modalLoading: false,
            itemData: {}
          }, this.reloadData);
          // fix 连续新建分类
          this.formInstance.resetFieldsValue();
        } else {
          message.error(res.msg || "新增配件分类失败");
          this.setState({
            modalLoading: false,
          });
        }
      })
    }
  }

  saveInstance = (instance) => {
    this.formInstance = instance;
  }

  render() {
    const columns = [
      {
        title: '配件分类',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        width: 250,
        render: (text, record) => {
          // 系统分类
          if(this.state.type == '1'){
            return null
          } else {
            return (
              <span>
                <a href="#" onClick={(event) => this.handleEditItem(record, event)}>编辑</a>
                <Divider type="vertical" />
                <Popconfirm
                  title="确认删除此配件分类?"
                  onConfirm={() => this.handleDelItem(record._id)}
                  okText="确认"
                  cancelText="取消"
                >
                  <a href="#" className={styles.delBtnStyle}>
                    删除
                  </a>
                </Popconfirm>
                {!record.toptypeid && <Divider type="vertical" /> }
                {!record.toptypeid && <a href="#" onClick={event=> this.handleCreateItem(record, event)}>添加子分类</a> }
              </span>
            )
          }
        }
      },
    ];

    const { modalVisible, modalLoading, itemData, type, toptypeid} = this.state;
    const { isLoading, custom, system } = this.props;
    const list = type == '0' ? custom : system;
    const that = this;

    const extraContent = (
      <div className={styles.extraContent}>
        <RadioGroup
          value={type}
          onChange={e => {
            that.setState({ type: e.target.value }, () => {
              that.reloadData();
            });
          }}
        >
          <RadioButton value="0">自定义</RadioButton>
          <RadioButton value="1">系统</RadioButton>
        </RadioGroup>
        <Search className={styles.extraContentSearch}
          placeholder="输入关键字"
          enterButton
          all
          onSearch={(v, e) => {
            that.setState({ key: v }, () => {
              that.reloadData()
            })
          }} />
        <Button type="primary" disabled={type=="1"}
          onClick={event=>this.handleCreateItem(null, event)}
        >新增</Button>
      </div>
    );

    return (
      <Card
        bordered={false}
        title={'配件分类管理'}
        style={{ marginTop: 24 }}
        bodyStyle={{ padding: '1px 0px 0px 0px' }}
        extra={extraContent}
      >
        <Table
          columns={columns}
          loading={isLoading}
          dataSource={list}
          rowKey="_id"
          childrenColumnName="subtype"
          pagination={false}
        />

        <Modal
          title={itemData._id ? "编辑" : "新建"}
          width={600}
          visible={modalVisible}
          confirmLoading={modalLoading}
          onOk={this.handleModalOk}
          onCancel={this.handleModalCancel}
        >
          <PartsCategoryItem
            saveInstance={this.saveInstance}
            onSaveForm={this.handleSaveForm}
            // ref={this.formRef}
            data={itemData}
            toptypeid={toptypeid}
          />
        </Modal>
      </Card>
    );
  }
}